package com.icbc.util;

import com.icbc.api.AESKeyGen;
import com.icbc.api.crypt.RSA;
import com.icbc.api.internal.util.codec.Base64;
import com.icbc.util.SM2Utils;

import javax.crypto.KeyGenerator;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Random;


/**
 * 生成密钥的工具类
 *
 * @author zxc
 */
public class GenerateKeyUtils {

    /**
     * 生成AES的密钥，经过base64编码
     */
    public static void generateAESKey() {
        int keySize = 128;
        String keyPath = "AESKey.txt";
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(keySize);
            byte[] encoded = kgen.generateKey().getEncoded();
            String key = Base64.encodeBase64String(encoded);
            AESKeyGen.saveKey(keyPath, key);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成SM2密钥并输出到控制台
     */
    public static void generateSM2KeyPair() {
        try {
            SM2Utils.generateKeyPair();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成RSA的密钥到指定文件
     */
    public static void generateRSAKeyPair() {
        try {
            OutputStream priOs = new FileOutputStream("rsaPri.pri");
            OutputStream pubOs = new FileOutputStream("rsaPub.pub");
            RSA.genRsaWithoutNewline(2048, priOs, pubOs);
        } catch (Exception var4) {
            var4.printStackTrace();
        }
    }


    /**
     * 生成SM4密钥并输出到控制台
     */
    public static String generateSM4Key() {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
